/* eslint react/no-string-refs:0 */
import React, { Component } from 'react';
import { Feedback } from '@icedesign/base';
import AuthForm from './AuthForm';
import axios from 'axios'
export default class LoginFrom extends Component {
  static displayName = 'LoginFrom';

  static propTypes = {};

  static defaultProps = {};

  formChange = (value) => {
    console.log('formChange:', value);
  };

  handleSubmit = (e) => {
    const url = "http://zzuisa.cn/reader/user/login";
    e.preventDefault();
    this.refs.form.validateAll((errors, values) => {

      if (errors) {
        console.log('errors', errors);
        return;
      }
      axios.defaults.withCredentials = true;
      const param = new URLSearchParams();
      param.append('username', values.username);
      param.append('password', values.password);
      axios.post(url, param,
        {
          withCredentials: true
        }

      ).then((res) => {
        console.log('res', res)
        console.log('values', values)
        if (res.data.code === 0) {
          cookie.save('username', res.data.data.nickname, {
            maxAge: 300,
          })
          cookie.save('role', res.data.data.role, {
            maxAge: 300,
          })
          cookie.save('uid', res.data.data.id, {
            maxAge: 300,
          })
          cookie.save('token', res.data.data.token, {
            maxAge: 300,
          })
          Feedback.toast.success("您好！" + res.data.data.nickname);
          this.props.history.push('/')
        }
        else
          Feedback.toast.error(res.data.message);
      })
    });
  };

  render() {
    const config = [
      {
        label: '用户名',
        component: 'Input',
        componentProps: {
          placeholder: '用户名',
          size: 'large',
          maxLength: 20,
        },
        formBinderProps: {
          name: 'username',
          required: true,
          message: '必填',
        },
      },
      {
        label: '密码',
        component: 'Input',
        componentProps: {
          placeholder: '密码',
          htmlType: 'password',
        },
        formBinderProps: {
          name: 'password',
          required: true,
          message: '必填',
        },
      },
      {
        label: '记住账号',
        component: 'Checkbox',
        componentProps: {},
        formBinderProps: {
          name: 'checkbox',
        },
      },
      {
        label: '登录',
        component: 'Button',
        componentProps: {
          type: 'primary',
        },
        formBinderProps: {},
      },
    ];


    const links = [
      { to: '/#', text: '立即注册' },
      { to: '/#', text: '找回密码' },
    ];

    return (
      <AuthForm
        title="登录"
        history={this.props.history}
        config={config}
        formChange={this.formChange}
        handleSubmit={this.handleSubmit}
        links={links}
      />
    );
  }
}
